/*
 * Copyright 2017 M. Eric DeFazio.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package varcode.load;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import varcode.LoadException;
import varcode.load.Source.SourceStream;


/**
 * A SourceStream that represents reading source from a file in a Jar 
 * or Zip file (usually on the ClassPath)
 *
 * @author M. Eric DeFazio eric@varcode.io
 */
public class FileInJarSourceStream
    implements SourceStream
{
    private final String pathToJar;
    private final String sourceId;
    private final InputStream inputStream;
    
    public FileInJarSourceStream( 
        String pathToJar, String sourceId, InputStream is )
    {
        this.pathToJar = pathToJar;
        this.sourceId = sourceId;
        this.inputStream = is;
    }
    
    @Override
    public InputStream getInputStream()
    {
        return inputStream;
    }

    @Override
    public String getSourceId()
    {
        return sourceId;
    }

    @Override
    public String describe()
    {
        return "[JAR:" + pathToJar + "]";
    }

    @Override
    public String asString()
        throws LoadException
    {
        try
        {
            return getFileContent( this.inputStream, "UTF-8" );
        }
        catch( IOException ioe ) 
        {
            throw new LoadException(
                "Unable to return the content of the stream as a String", ioe );
        }
    }
    
    private static String getFileContent( InputStream fis, String encoding ) 
        throws IOException
    {
        try
        {
            BufferedReader br = new BufferedReader( 
                new InputStreamReader( fis, encoding ) );
            StringBuilder sb = new StringBuilder();
            String line;
            while(( line = br.readLine()) != null ) 
            {
                sb.append( line );
                sb.append( '\n' );
                
            }
            return sb.toString();
        }
        catch( IOException ioe )
        {
            throw new LoadException( 
                "Unable to get the String from the Stream", ioe );
        }        
    }
    
    @Override
    public String toString()
    {
        return describe();
    }
}
